package io

import (
	"fmt"
	"net"
	"remoteGo/remote/coder"
)

type TCPSocket struct {
	conn  net.Conn
	coder coder.Coder
}

func NewTCPClientSocket(conn net.Conn) *TCPSocket {
	return &TCPSocket{
		conn:  conn,
		coder: coder.GetGobCoder(),
	}
}

func NewTCPSocket(address string) (*TCPSocket, error) {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return nil, err
	}
	return NewTCPClientSocket(conn), nil
}

func (s *TCPSocket) Send(x interface{}) error {
	return s.coder.Encode(s.conn, x)
	//l := len(buf)
	//p := 0
	//for p < l {
	//	n, err := s.conn.Write(buf[p:])
	//	if err != nil {
	//		return err
	//	}
	//	p += n
	//}
	//return nil
}

func (s *TCPSocket) Recv(x interface{}) error {
	//n, err := s.conn.Read(buf)
	return s.coder.Decode(s.conn, x)
}

func (s *TCPSocket) Close() error {
	return s.conn.Close()
}

type TCPServerSocket struct {
	server net.Listener
}

func NewTCPServerSocket(address string) *TCPServerSocket {
	fmt.Println(address)
	server, err := net.Listen("tcp", address)
	if err != nil {
		panic(err)
	}
	return &TCPServerSocket{
		server: server,
	}
}

func (t *TCPServerSocket) Accept() (Socket, error) {
	conn, err := t.server.Accept()
	if err != nil {
		return nil, err
	}
	return NewTCPClientSocket(conn), nil
}

func (t *TCPServerSocket) Close() error {
	return t.server.Close()
}
